/*
 * File      : fal_flash_sfud_port.c
 * This file is part of FAL (Flash Abstraction Layer) package
 * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, _write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-01-26     armink       the first version
 */

#include <cstdarg>
#include <logger_rte.h>
#include "port/fal/inc/fal.h"
#include "port/sfud/inc/sfud.h"

#ifdef FAL_USING_SFUD_PORT
#ifdef RT_USING_SFUD
#include <spi_flash_sfud.h>
#endif

#ifndef FAL_USING_NOR_FLASH_DEV_NAME
#define FAL_USING_NOR_FLASH_DEV_NAME             "norflash0"
#endif

#include "SPIFlash.h"

extern SPIFlash fspi;
extern "C"
{
static int spiinit(void);

static int _read(long offset, uint8_t *buf, size_t size);

static int _write(long offset, const uint8_t *buf, size_t size);

static int _erase(long offset, size_t size);

struct fal_flash_dev nor_flash0 =
        {FAL_USING_NOR_FLASH_DEV_NAME, 8 * 1024 * 1024, 8 * 1024 * 1024, 4096, {spiinit, _read, _write, _erase}, 1};
static int spiinit(void) {


    /* RT-Thread RTOS platform */
    /* bare metal platform */


    /* update the flash chip information */
        fspi.init();
        // nor_flash0.blk_size = fspi.blockSize();
        // nor_flash0.len = fspi.capacity();

    return 0;
}

    static int _read(long offset, uint8_t *buf, size_t size)
    {
        fspi.readBytes(nor_flash0.addr + offset, buf, (u16) size);

    return size;
}

    static int _write(long offset, const uint8_t *buf, size_t size)
    {
        fspi.writeBytes(nor_flash0.addr + offset, buf, (u16) size);
    return size;
}

    static int _erase(long offset, size_t size)
    {
        fspi.blockErase4K(nor_flash0.addr + offset);
    return size;
}


/* args point to the first variable parameter */
/* must use vprintf to print */
}

/**
 * This function is print routine info.
 *
 * @param format output format
 * @param ... args
 */

/* args point to the first variable parameter */
/* must use vprintf to print */
#endif /* FAL_USING_SFUD_PORT */
